/* eslint-disable react/jsx-key */
import React, { useState, useRef, useMemo } from 'react';
import ReactDOM from 'react-dom';
import { Card, Switch, Button, Modal, message, Popconfirm, Tooltip } from 'antd';
import AutoTable from '@/components/AutoTable';
import InitForm from '@/components/InitForm';
import { submit_to_keeper, complete_rescind } from '@/services/business';
import { connect } from 'umi';
import { PlusOutlined } from '@ant-design/icons';
import { company } from '@/services/business';
import { getFetch } from '@/utils/doFetch';
import CompanyDetail from '@/components/CompanyDetail';
import moment from 'moment';
import CompanyName from '@/components/CompanyName';

// type 类型有 table treeselect upload inputnumber datepicker daterange radio select textarea autoinput editor password input

let defaultFields = (userid) => {
    return {
      company_id: {
        value: null,
        type: 'select',
        title: '代账公司',
        name: ['company_id'],
        required: true,
        options: {
          database: company,
          params: {
            is_all: 1,
            type: -1,
            account_user_id: userid,
            status: 'completed',
            service_type: 'account',
          },
        },
        col: { span: 24 },
      },
      reason: {
        value: null,
        type: 'select',
        title: '解约原因',
        name: ['reason'],
        required: true,
        options: [
          {
            label: '价格',
            value: '价格',
          },
          {
            label: '转注销',
            value: '转注销',
          },
          {
            label: '其它',
            value: '其它',
          },
        ],
        col: { span: 24 },
      },
      remark: {
        value: null,
        type: 'textarea',
        title: '备注',
        name: ['remark'],
        required: false,
        col: { span: 24 },
      },
    };
  },
  shFields = {
    reason: {
      value: null,
      type: 'select',
      title: '解约原因',
      name: ['reason'],
      required: true,
      options: [
        {
          label: '价格',
          value: '价格',
        },
        {
          label: '转注销',
          value: '转注销',
        },
        {
          label: '其它',
          value: '其它',
        },
      ],
      col: { span: 24 },
    },
    remark: {
      value: null,
      type: 'textarea',
      title: '备注',
      name: ['remark'],
      required: false,
      col: { span: 24 },
    },
    fallback_message: {
      value: null,
      type: 'textarea',
      title: '客户反馈信息',
      name: ['fallback_message'],
      required: true,
      col: { span: 24 },
    },
  },
  status = {
    area_director_pending: '区域主管审核中',
    area_account_pending: '区域会计审核中',
    wait_for_repair: '待补缴',
    wait_for_keeper: '保管员待交接',
    completed: '已完成',
    cancel: '已取消',
  };

function CompleteRescind(props) {
  const [vs, cvs] = useState(false), //表单显/隐
    [fields, cf] = useState(defaultFields(props.user.currentUser.id)),
    [iftype, ciftype] = useState({});

  let actionRef = useRef(),
    ChildRef = null;
  function reload() {
    actionRef?.current?.reload();
    ChildRef?.onRefresh();
  }
  const columns = useMemo(() => {
    return [
      {
        title: '公司名称',
        width: 260,
        dataIndex: 'company_name',
        key: 'company_name',
        render: (_, row) => (
          <CompanyName
            row={{ ...row, name: row?.company_name ?? row?.name, id: row?.company_id ?? row?.id }}
            reload={reload}
          />
        ),
      },
      {
        title: '解约原因',
        dataIndex: 'reason',
        key: 'reason',
        search: false,
      },
      {
        title: '备注',
        dataIndex: 'remark',
        key: 'remark',
        search: false,
      },
      {
        title: '客户反馈信息',
        dataIndex: 'fallback_message',
        key: 'fallback_message',
        search: false,
      },
      {
        title: '解约日期',
        dataIndex: 'created_at',
        key: 'created_at',
        search: false,
        render: (_, row) => <span>{moment(row?.created_at).format('YYYY-MM-DD HH:mm:ss')}</span>,
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        search: false,
        render: (_, row) => <span>{status[row.status]}</span>,
      },

      {
        title: '操作',
        valueType: 'option',
        width: 80,
        render: (text, record, _, action) => [
          <Popconfirm
            placement="bottom"
            title={"是否交接完成,点击'是'则完成解约流程？"}
            onConfirm={() => {
              complete_rescind({ id: record.id }).then((res) => {
                if (res.code == 0) {
                  message.success('操作成功');
                  reload();
                }
              });
            }}
            okText="是"
            cancelText="否"
            disabled={record.status != 'wait_for_keeper'}
          >
            <a disabled={record.status != 'wait_for_keeper'}>交接完成</a>
          </Popconfirm>,
        ],
      },
    ];
  }, []);

  let saveData = (values) => {
    let { dispatch } = props;
    if (iftype.val == 'add') {
      dispatch({
        type: 'business/addrescind',
        payload: values,
      }).then((res) => {
        if (res.code == 0) {
          message.success('操作成功');
          reload();
          cvs(false);
        }
      });
    } else if (iftype.val == 'audit') {
      dispatch({
        type: 'business/submit_to_account',
        payload: { ...values, id: iftype.id },
      }).then((res) => {
        if (res.code == 0) {
          message.success('操作成功');
          reload();
          cvs(false);
        }
      });
    }
  };

  return (
    <div className="pgcontainer">
      <AutoTable
        pagetitle={props.route.name} //页面标题
        columns={columns}
        actionRef={actionRef}
        onRef={(node) => (ChildRef = node)}
        extraparams={{ status: 'wait_for_keeper' }}
        path="/wbn-api/rescind"
        //withCard={false}
        //cardtitle = "name" //卡片标题
        //cardavatar = "img_url" //卡片头像
      />
      <Modal
        maskClosable={false}
        title={iftype.title}
        open={vs}
        onCancel={() => cvs(false)}
        footer={false}
        width={iftype.val == 'detail' ? 1200 : 600}
        destroyOnClose={true}
      >
        {iftype.val == 'detail' ? (
          <CompanyDetail id={iftype.id || ''} />
        ) : (
          <InitForm
            fields={fields}
            submitData={(values) => {
              saveData(values);
            }}
            onChange={(changedValues, allValues) => {
              //联动操作
            }}
            submitting={
              props.loading.effects['business/addrescind'] ||
              props.loading.effects['business/editrescind'] ||
              !vs
            }
          />
        )}
      </Modal>
    </div>
  );
}

export default connect(({ business, user, loading }) => ({
  business,
  loading,
  user,
}))(CompleteRescind);
